<template>
  <div class="device-container">
    <div class="device-detail">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>设备管理</el-breadcrumb-item>
        <el-breadcrumb-item>设备</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- <breadcrumb :items="breadcrumbItems" /> -->
      <h1 style="margin: 15px auto">{{ title }}</h1>
      <div style="display: flex">
        <el-dropdown id="a" trigger="click" @command="handleCommand">
          <el-select
            v-model="productId"
            style="width: 150px; margin-left: auto"
            placeholder="选择产品"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>

          <el-icon><ArrowDownBold></ArrowDownBold></el-icon>
        </el-dropdown>
        <div class="b">
          <el-tag type="danger" style="width: 80px"
            >设备总数 <el-icon><QuestionFilled /></el-icon
          ></el-tag>
          <div style="margin-top: 20px">
            <el-text tag="b" size="">{{ counts[0] }}</el-text>
          </div>
        </div>
        <div class="b">
          <el-tag type="info" style="width: 80px"
            >激活设备 <el-icon><QuestionFilled /></el-icon
          ></el-tag>
          <div style="margin-top: 20px">
            <el-text tag="b" size="large">{{ counts[1] }}</el-text>
          </div>
        </div>
        <div class="b">
          <el-tag type="success" style="width: 80px"
            >当前在线 <el-icon><QuestionFilled /></el-icon
          ></el-tag>

          <div style="margin-top: 20px">
            <el-text tag="b" size="large">{{ counts[2] }}</el-text>
          </div>
        </div>
      </div>
      <el-button type="primary" @click="open">
        <el-icon><Plus /></el-icon>添加设备</el-button
      >
      <el-dialog
        title="添加设备"
        v-model="inserterTag"
        width="50%"
        @close="inserterTag = false"
      >
        <el-form ref="form" :model="newDevice" label-width="200px">
          <el-form-item label="产品" :required="true">
            <el-cascader
              style="width: 70%"
              :options="options"
              v-model="pids"
              clearable
            ></el-cascader>
          </el-form-item>
          <el-form-item label="设备类型" :required="true">
            <el-cascader
              style="width: 70%"
              :options="types"
              v-model="tids"
              clearable
            ></el-cascader>
          </el-form-item>

          <el-form-item label="设备编号(同个产品的索引)" :required="true">
            <el-input
              type="number"
              v-model="newDevice.deviceIndex"
              style="width: 70%"
            ></el-input>
          </el-form-item>

          <el-form-item label="父设备(非必选项)">
            <el-input
              type="number"
              v-model="newDevice.parentId"
              style="width: 70%"
            ></el-input>
          </el-form-item>

          <el-form-item label="产品名称" :required="true">
            <el-input v-model="newDevice.name" style="width: 70%"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="addDevice">提交</el-button>
            <el-button @click="this.inserterTag = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>

    <el-table :data="devices" border style="width: 80%; margin-left: 40px">
      <el-table-column prop="name" label="设备名称"></el-table-column>
      <el-table-column prop="productId" label="所属产品编号"></el-table-column>
      <el-table-column prop="deviceKey" label="设备编号"></el-table-column>
      <el-table-column label="设备激活状态" type="flex" align="center">
        <template v-slot="scope">
          <el-button type="success" v-if="scope.row.active == 1"
            >已激活</el-button
          >
          <el-button type="warning" v-else>未激活</el-button>
        </template>
      </el-table-column>
      <el-table-column label="开关设备">
        <template v-slot="scope">
          <el-button type="primary" @click="switchDevice(scope.row)"
            >发起指令</el-button
          >
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        type="flex"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" type="flex" align="center">
        <template v-slot="scope">
          <el-button type="primary" icon="Edit" @click="editDevice(scope.row)">
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            @click="delDevice(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 10px"
      background
      layout="prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :total="devicePageBean.total"
      :page-size="devicePageBean.pageSize"
    ></el-pagination>

    <el-dialog
      title="发送指令"
      v-model="switchTag"
      width="50%"
      @close="switchClosed"
    >
      <el-form :model="directive" label-width="auto" style="max-width: 600px">
        <el-form-item label="设备名称">
          <el-input v-model="directive.cmdName" />
        </el-form-item>
        <el-form-item label="设备Key">
          <el-input v-model="directive.deviceKey" />
        </el-form-item>
        <el-form-item label="继电器编号">
          <el-input v-model="directive.deviceSubCode" />
        </el-form-item>
        <el-form-item label="开关指令">
          <el-input v-model="directive.value"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="sendDirective">确定</el-button>
          <el-button @click="switchClosed">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
  
  <script>
import md5 from "js-md5";
import Base64 from "js-base64";
import { ElMessageBox } from "element-plus";
//   import Breadcrumb from '@/components/Breadcrumb.vue'; // Assuming you have a Breadcrumb component
export default {
  name: "Device",
  data() {
    return {
      products: [],
      devicePageBean: {
        pageNum: 1,
        pageSize: 5,
      },
      devices: [],
      title: "设备管理",
      productId: "",
      options: [],
      tenantId: "1658095188329779300",
      tenant: {},
      inserterTag: false,
      deviceTpes: [],
      types: [],
      newDevice: {},
      tids: [],
      pids: [],
      counts: [],
      switch_device: {},
      switchTag: false,
      directive: {
        deviceKey: "",
        cmdName: "",
        deviceSubCode: "",
        value: 0,
      },
    };
  },
  computed: {},
  methods: {
    load(){
      this.getProducts();
      this.listDevices();
      this.loadDeviceTypes();
      this.countDevices();
      this.getTenant();
    },
    md5ToBase64(str) {
      // 计算MD5
      const hash = md5(str);
      // 将MD5散列值转换为Uint8Array，以便Base64编码
      const hashBuffer = new Uint8Array(
        hash.match(/[\da-f]{2}/gi).map((h) => parseInt(h, 16))
      );
      // 进行Base64编码
      const base64Hash = Base64.encode(hashBuffer);
      return base64Hash;
    },
    sendDirective() {
      var sign = this.tenant.accessKey + this.tenant.accessSecurity;
      this.$axios({
        method: "POST",
        url: "auth/pub",
        headers: {
          "access-key": this.tenant.accessKey,
          "access-security": this.tenant.accessSecurity,
          sign: sign,
        },
        data: this.directive,
      })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    switchClosed() {
      this.switchTag = false;
      this.switch_device = {};
      this.directive = {};
    },
    switchDevice(row) {
      this.switch_device = row;
      this.directive.deviceKey = row.deviceKey;
      this.directive.cmdName = row.name;
      this.switchTag = true;
    },
    countDevices() {
      this.$axios({
        url: "device/count",
        method: "GET",
        params: {
          tenantId: this.tenantId,
        },
      }).then((res) => {
        this.counts = res.data;
      });
    },
    addDevice() {
      this.newDevice.productId = this.pids[0];
      this.newDevice.deviceTypeId = this.tids[0];
      this.newDevice.tenantId = this.tenantId;
      this.newDevice.createTime = new Date();
      this.newDevice.updateTime = new Date();

      let d = {
        id: 2,
        name: this.newDevice.name,
        deviceKey: "0",
        deviceTypeId: this.newDevice.deviceTypeId,
        deleted: 0,
        productId: this.newDevice.productId,
        parentId: this.newDevice.parentId,
        tenantId: this.tenantId,
        groupId: "0",
        active: 0,
        deviceSecret: "0",
        deviceIndex: this.newDevice.deviceIndex,
      };
      this.$axios({
        url: "device/add",
        method: "POST",
        data: d,
        headers: {
          "Content-Type": "application/json",
        },
      }).then((res) => {
        this.inserterTag = false;
      });
    },
    loadDeviceTypes() {
      this.$axios({
        url: "device/types",
        method: "GET",
      }).then((res) => {
        this.deviceTpes = res.data;
        this.types = this.deviceTpes.map((item) => {
          return {
            value: item.id,
            label: item.name,
          };
        });
      });
    },
    open() {
      this.inserterTag = true;
    },
    editDevice(row) {
      this.$router.push({
        path: `/IoT/deviceChild/${row.id}`,
      });
    },
    delDevice(device) {
      this.$axios({
        method: "DELETE",
        url: "/device/" + device.id,
      })
        .then((res) => {
          if (res.data.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleCommand(val) {
      this.devicePageBean.pageSize = val;
      this.listDevices();
    },
    handleCurrentChange(val) {
      this.devicePageBean.pageNum = val;
      this.listDevices();
    },
    listDevices() {
      if (this.productId == null || this.productId == "") {
        this.fetchDevicesByTenantId();
      } else {
        this.fetchDeviceListByTenantId();
      }
    },
    //当productId为空，则查询所有设备
    fetchDevicesByTenantId() {
      this.$axios({
        url:
          "device/" +
          this.tenantId +
          "/" +
          this.devicePageBean.pageNum +
          "/" +
          this.devicePageBean.pageSize,
        methods: "GET",
      }).then((res) => {
        this.devicePageBean = res.data;
        this.devices = res.data.list;
      });
    },
    //当productId不为空，则查询该产品下的所有设备
    fetchDeviceListByTenantId() {
      this.$axios({
        url: `device/${this.tenantId}/${this.productId}/${this.devicePageBean.pageNum}/${this.devicePageBean.pageSize}`,
        method: "GET",
      }).then((response) => {
        this.devicePageBean = response.data;
        this.devices = response.data.list;
      });
    },
    //获取产品列表
    getProducts() {
      console.log(this.tenantId);
      this.$axios({
        url: "/product/byts/" + this.tenantId,
        mehthod: "GET",
      })
        .then((res) => {
          if (res.code == 200) {
            this.products = res.data;
            this.options = this.products.map((item) => {
              return {
                value: item.id,
                label: item.name,
              };
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeList() {
      this.listDevices();
    },
    getTenant() {
      this.$axios({
        method: "POST",
        url: "tenant/get/",
        data: {
          tenantId: this.tenantId,
        },
      })
        .then((res) => {
          if (res.code == 200) {
            this.tenant = res.data;
            console.log(this.tenant);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  components: {},
  mounted() {
    // Fetch device data from API
    this.tenantId = sessionStorage.getItem("tenantId");
    
  },created(){  
    this.load();
  },
  watch: {
    productId(val) {
      this.productId = val;
      this.changeList();
    },
  },
};
</script>
  <style scoped>
.device-detail {
  padding: 20px;
}

.device-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.device-item {
  border: 1px solid #ccc;
  padding: 10px;
}
#a {
  margin: 20px;
}
.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
.b {
  margin-left: 90px;
}
</style>